package com.ruiboyun.liveapp.util.tool;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Base64;
import android.view.View;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by 吴世芊 on 2015/12/25 11:38.
 * 邮箱:apple9302@126.com
 * 公司:浙江答分奇网络技术有限公司
 * 项目名：DaFenQiStudent
 * 包名：com.zhihuitong.dafenqistudent.toolclass
 * 类功能描述：
 */
public class ProcessImage {
    //质量压缩方法,压缩图片到多少kb
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }
    /**
     * 把Bitmap转Byte
     */
    public static byte[] BitmapToBytes(Bitmap bm){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    //图片按比例大小压缩方法（根据路径获取图片并压缩）
    public static Bitmap getimage(String srcPath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);//此时返回bm为空

        options.inJustDecodeBounds = false;
        int w = options.outWidth;
        int h = options.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (options.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (options.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        options.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, options);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }
    //图片按比例大小压缩方法（根据Bitmap图片压缩）
    public static Bitmap comp(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }
    //保存图片 并且生成图片uri
    public static String saveImage(Bitmap bitmap) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File rootDir = new File(Environment.getExternalStorageDirectory() + File.separator + "yihuan/image");
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }
            try {
                File img = new File(rootDir.getAbsolutePath(), UUID.randomUUID().toString()+".png");
                FileOutputStream fos = new FileOutputStream(img);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();

                return img.getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static Bitmap getViewBitmap(View view, Context context,int width,int height){
        view.setDrawingCacheEnabled( true );
        Bitmap bitmap = null;
        try{
            if( null != view.getDrawingCache( ) ){
                bitmap = Bitmap.createScaledBitmap(view.getDrawingCache(), width, height, false);

            }
        }catch( OutOfMemoryError e ){
            e.printStackTrace( );
        }finally{
            view.setDrawingCacheEnabled( false );
            view.destroyDrawingCache( );
        }
        return bitmap;

    }
    public static String getViewFile(View view, Context context,int width,int height){
        view.setDrawingCacheEnabled( true );
        Bitmap bitmap = null;
        try{
            if( null != view.getDrawingCache( ) ){
                bitmap = Bitmap.createScaledBitmap(view.getDrawingCache(), width, height, false);
                return saveImage(bitmap);
            }
        }catch( OutOfMemoryError e ){
            e.printStackTrace( );
        }finally{
            view.setDrawingCacheEnabled( false );
            view.destroyDrawingCache( );
        }
        return null;
    }
    public static Bitmap big(Bitmap bitmap,float width,float height) {
        Matrix matrix = new Matrix();
        matrix.postScale(width, height); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }
    public static Bitmap small(Bitmap bitmap,float width,float height) {
        Matrix matrix = new Matrix();
        matrix.postScale(width, height); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }
    public static Bitmap scaleImage(Bitmap bitmap,float needWidth,float needHeight){
        Matrix matrix = new Matrix();
        matrix.setScale(needWidth/bitmap.getWidth(), needHeight/bitmap.getHeight()); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }
    public static Bitmap getBitmap(String filePath,int needWidth,int needHeight){
        //加载图像的尺寸，而非图形本身
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        Bitmap bitmap= BitmapFactory.decodeFile(filePath, options);
        //图形实际宽高与需要显示宽高之间的比率,则为压缩比率
        int widthRadio=(int) Math.ceil(options.outWidth / needWidth);
        int heightRadio=(int) Math.ceil(options.outHeight / needHeight);
        if (heightRadio>1&&widthRadio>1){
            if (heightRadio>widthRadio){
                options.inSampleSize=heightRadio;
            }else {
                options.inSampleSize=widthRadio;
            }

        }
        //对图片进行真正的解码
        options.inJustDecodeBounds=false;
        bitmap= BitmapFactory.decodeFile(filePath, options);
        return bitmap;
    }
    public static int caculateSampleSize(BitmapFactory.Options options,int needWidth,int needHeight){
        int widthRadio=(int) Math.ceil(options.outWidth / needWidth);
        int heightRadio=(int) Math.ceil(options.outHeight / needHeight);
        int sampleSize=1;
        if (heightRadio>1&&widthRadio>1){
            sampleSize=heightRadio>widthRadio?heightRadio:widthRadio;
            options.inSampleSize=heightRadio>widthRadio?heightRadio:widthRadio;
        }
        return sampleSize;
    }
    public static Bitmap getBitmap(Context context,int resId,int needWidth,int needHeight){
        //加载图像的尺寸，而非图形本身
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(), resId, options);
        //图形实际宽高与需要显示宽高之间的比率,则为压缩比率(Math.ceil()向上取整)
       options.inSampleSize=caculateSampleSize(options,needWidth,needHeight);
        //对图片进行真正的解码
        options.inJustDecodeBounds=false;
        bitmap= BitmapFactory.decodeResource(context.getResources(), resId, options);
        return bitmap;
    }
    /**
     * @param activity
     * @param x        截图起始的横坐标
     * @param y        截图起始的纵坐标
     * @param width
     * @param height
     * @return
     */
    private Bitmap getBitmap(Activity activity, int x, int y, int width, int height) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap;//生成的位图

        bitmap = view.getDrawingCache();
        //边界处理,否则会崩滴
        if (x < 0)
            x = 0;
        if (y < 0)
            y = 0;
        if (x + width > bitmap.getWidth()) {
            //保持不改变,截取图片宽高的原则
            x = bitmap.getWidth() - width;
        }
        if (y + height > bitmap.getHeight()) {
            y = bitmap.getHeight() - height;
        }
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        bitmap = Bitmap.createBitmap(bitmap, x, y, width, height);
        view.setDrawingCacheEnabled(false);
        return bitmap;
    }
    public static String BitmapToString(Bitmap bitmap){
        String imgArray=null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            byte[] bytearray = bos.toByteArray();
            imgArray= new String(Base64.encodeToString(bytearray, Base64.DEFAULT));
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgArray;
    }
    public static int getMipmap(Context context,String id){
        int mipmap = context.getResources().getIdentifier(id, "mipmap", context.getPackageName());
        return mipmap;
    }
    public static Bitmap drawableToBitmap(Drawable drawable){
        Bitmap bitmap=Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),
                drawable.getOpacity()!= PixelFormat.OPAQUE?Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565);
        Canvas canvas=new Canvas(bitmap);
        Paint paint=new Paint();
        drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
    public static Drawable bitmapToDrawable(Context context,Bitmap bitmap){
        Drawable drawable=new BitmapDrawable(context.getResources(),bitmap);
        return drawable;
    }
}
